package com.dataseek.iot.mongodb.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dataseek.iot.mongodb.service.IMongoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;


/**
 * @author cc
 * @Title: mongodb 服务
 * @Description: mongodb 服务
 * @date 2021/10/36:48 下午
 * @since 1.0
 */
@Service
@Slf4j
public class MongoService implements IMongoService<JSONObject> {

    @Autowired
    private MongoOperations mongoOperations;


    //存在则更新，不存在则插入
    @Override
    public void save(JSONObject entity) {
        mongoOperations.save(entity);
    }

    //insert存在则不做处理，不存在则插入
    @Override
    public void insert(JSONObject entity) {
        mongoOperations.insert(entity);
    }

    //根据userid删除文档
    @Override
    public void remove(String uid) {
        Query query = new Query();
        query.addCriteria(Criteria.where("messageId").is(uid));
        mongoOperations.remove(query);
    }

    //TODO 日志信息没有更新
    @Override
    public void update(JSONObject log) {
    }

    @Override
    public List<JSONObject> findByUid(String uid) {
        Query query = new Query();
        query.addCriteria(Criteria.where("messageId").is(uid));
        return mongoOperations.find(query, JSONObject.class);
    }

    @Override
    public List<JSONObject> findByUidAndTimestamp(String uid, String timestamp) {
        Query query = new Query();
        query.addCriteria(Criteria.where("messageId").is(uid).and("timestamp").is(timestamp));
        return mongoOperations.find(query, JSONObject.class);
    }

    @Override
    public List<JSONObject> page(int page, String uid) {
        return null;
    }

    //根据DeviceId 查询日志
    public List<JSONObject> findByDeviceId(String uid){
        Query query = new Query();
        query.addCriteria(Criteria.where("deviceId").is(uid));
        return mongoOperations.find(query,JSONObject.class);
    }

    //根据deviceId 查询最新的日志信息
    public List<JSONObject> findTheLatestLogByDeviceId(String uid){
        Query query = new Query();
        query.addCriteria(Criteria.where("deviceId").is(uid));
        mongoOperations.find(query, JSONObject.class).sort(new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                return o1.getTimestamp("timestamp").compareTo(o2.getTimestamp("timestamp"));
            }
        });
      return null;
    }

}
